package com.yj.timecapsule.service.likes.impl;

import cn.hutool.core.date.StopWatch;
import com.yj.timecapsule.common.context.LoginUserContext;
import com.yj.timecapsule.entity.likes.Likes;
import com.yj.timecapsule.mapper.LikesMapper;
import com.yj.timecapsule.service.likes.LikesService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author Sean
 * @CreateTime 2024-08-03  15:58
 * @Description
 * @Version 1.0
 */
@Service
public class LikesServiceImpl implements LikesService {
    @Resource
    private LikesMapper likesMapper;

    @Override
    public Map<Long, Boolean> assertLikes(List<Long> diaryIds) {
        // TODO 数据量大时候查询速度较慢
        Long currentUserId = LoginUserContext.getId();
        List<Likes> likesList = likesMapper.selectByDiaryIds(diaryIds);
        Map<Long, Boolean> result = new HashMap<>(diaryIds.size());
        result.putAll(diaryIds.stream().collect(HashMap::new, (m, v) -> m.put(v, false), HashMap::putAll));
        likesList.forEach(likes -> {
            result.put(likes.getDiaryId(), currentUserId.equals(likes.getUserId()));
        });

        return result;
    }


    @Override
    public void like(Long diaryId) {
        Long currentId = LoginUserContext.getId();
        Likes likes = likesMapper.selectByUserIdAndDiaryId(currentId, diaryId);
        if (likes == null) {
            likes = new Likes();
            likes.setDiaryId(diaryId);
            likes.setUserId(currentId);
            likesMapper.insertSelective(likes);
            return;
        }
        likesMapper.deleteByUserIdAndDiaryId(currentId, diaryId);
    }
}
